<template>
  <div class="app-container" ref="appContainer">
    <div class="conversion-table">
      <PropTable
        :columns="userStore.rolescode!=15 ? column : column2"
        :data="list"
        :total="total"
        @reset="reset"
        @onSubmit="onSubmit"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
        @exportExcelAction="exportExcelAction"
      >
        <template #btn>
          <div style="display: flex; justify-content: flex-end">
            <el-button type="primary" @click="handleAdd"
            v-if="userStore.rolescode!=15"
              ><el-icon><plus /></el-icon> 添加</el-button
            >
          </div>
        </template>
        <template v-slot:operation="scope">
          <div style="display: flex; justify-content: flex-end">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handeleEdit(scope.row)"
              v-if="userStore.rolescode!=15"
            >
              编辑
            </el-button>
            <el-button
              link
              type="success"
              icon="Delete"
              @click="handelDelete(scope.row)"
              v-if="userStore.rolescode!=15"
              >删除
            </el-button>
          </div>
        </template>
      </PropTable>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      :title="title"
      v-model="detailsvisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      style="background: #fff"
      destroy-on-close
    >
      <el-form :model="form" label-width="auto">
        <el-form-item label="一级名称">
          <el-input v-model="form.businessName" />
        </el-form-item>
        <el-form-item label="二级名称">
          <el-input
            v-model="form.businessNames"
            :disabled="isDisabled('businessNames')"
          />
        </el-form-item>

        <el-form-item label="三级名称">
          <el-input
            v-model="form.businessNameses"
            :disabled="isDisabled('businessNameses')"
          />
        </el-form-item>

        <div style="display: flex; justify-content: center">
          <el-button type="primary" v-if="userStore.rolescode!=15" @click="handelSubmit">确认</el-button>
          <el-button @click="cancel" v-if="userStore.rolescode!=15">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup >
import { ref, reactive, onMounted, nextTick } from "vue";
//@ts-ignore
import PropTable from "@/components/Table/PropTable/index.vue";
//@ts-ignore
import { exportExcel } from "@/utils/exprotExcel";
import { ElMessageBox, ElMessage } from "element-plus";

import { useRouter, useRoute } from "vue-router";
import {
  businessListApi,
  businessAddApi,
  businessDetailsApi,
  businessUpdateApi,
  businessDeleteApi,
} from "@/api/business/index";

import { useEmpty, formatDate } from "@/utils/index";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const loading = ref(true);
const detailsvisible = ref(false);

const route = useRoute();
const router = useRouter();

const businessoptions = ref([]);

const form = reactive({
  businessName: "",
  businessNames: "",
  businessNameses: "",
});

const title = ref("");
const column = [
  {
    name: "businessName",
    label: "一级名称",
    inSearch: true,
    valueType: "input",
  },
  {
    name: "businessNames",
    label: "二级名称",
    inSearch: true,
    valueType: "input",
  },

  {
    name: "businessNameses",
    label: "三级名称",
    inSearch: true,
    valueType: "input",
  },
  { name: "operation", slot: true, fixed: "right", width: 150, label: "操作" },
];
const column2 = [
  {
    name: "businessName",
    label: "一级名称",
    inSearch: true,
    valueType: "input",
  },
  {
    name: "businessNames",
    label: "二级名称",
    inSearch: true,
    valueType: "input",
  },

  {
    name: "businessNameses",
    label: "三级名称",
    inSearch: true,
    valueType: "input",
  }
];

const list = ref([]);

const businessDictionary = ref([]);

let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

const conversion = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };

  if (paramsSubmit) {
    for (let key in paramsSubmit) {
      if (paramsSubmit[key]) {
        params[key] = paramsSubmit[key];
      }
    }
  }

  const res = await businessListApi(params);
  if (res.code === 200) {
    list.value = res.rows;
    total.value = Number(res.total);
  } else {
    ElMessage.error(res.msg);
    // 进行提示
    loading.value = false;
  }
};

const reset = (val) => {
  val = "";
  conversion();
};

let paramsSubmit;

const onSubmit = (val) => {
  if (val) {
    val.projectCreateTime = formatDate(val.projectCreateTime);
    paramsSubmit = val;
    conversion();
  }
};

const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  list.value = [];
  conversion();
};
const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  list.value = [];
  conversion();
};

// 导出
function exportExcelAction(val) {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };
  if (val) {
    for (let key in val) {
      if (val[key]) {
        params[key] = val[key];
      }
    }
  }

  proxy.download(
    "/project/businessType/export",
    params,
    `业务类型_${new Date().getFullYear() +  '-' + new Date().getMonth() + 1 + '-' +new Date().getDate()}.xlsx`
  );
}

const type = ref("1");

// 添加
const handleAdd = () => {
  detailsvisible.value = true;
  title.value = "新增业务类型";
  type.value = "1";
};

const businessId = ref(0);
const businessBid = ref(0);
const businessCid = ref(0);

const disabled = ref(true);
let businessNames;
let businessNameses;

let name;

function isDisabled(fieldName) {
  if (type.value === "2") {
    if (
      fieldName === "businessNames" &&
      useEmpty(businessNames) &&
      useEmpty(businessNameses)
    ) {
      return (disabled.value = true);
    }
  
    if (fieldName === "businessNameses" && useEmpty(businessNameses)) {
      return (disabled.value = true);
    }
  }
}


// 

// 编辑
const handeleEdit = async (value) => {
  detailsvisible.value = true;

  title.value = "编辑业务类型";
  type.value = "2";


  let params = {};
  if (value && value.id) {
    params["id"] = value.id;
    params["bid"] = value.bid;
    params["cid"] = value.cid;
  }

  const response = await businessDetailsApi(params);

  if (response.code === 200 && response.data) {
    businessId.value = response.data.id;
    businessBid.value = response.data.bid;
    businessCid.value = response.data.cid;

    businessNames = response.data.businessNames;
    businessNameses = response.data.businessNameses;

    form.businessName = response.data.businessName;
    form.businessNames = response.data.businessNames;
    form.businessNameses = response.data.businessNameses;
  }

};

// 取消
const cancel = () => {
  detailsvisible.value = false;
  form.businessName = "";
  form.businessNames = "";
  form.businessNameses = "";
};

// 取消
const handleClose = () => {
  detailsvisible.value = false;
  form.businessName = "";
  form.businessNames = "";
  form.businessNameses = "";
};

// 确认
const handelSubmit = async () => {
  if (type.value === "1") {
    const response = await businessAddApi(form);
    if (response.code === 200) {
      // 添加成功的提示
      ElMessage.success(response.msg);
      //   关闭弹窗
      detailsvisible.value = false;
      // 更新列表
      await conversion();
      form.businessName = "";
      form.businessNames = "";
      form.businessNameses = "";
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    if (businessId.value) {
      form["id"] = businessId.value;
      form["bid"] = businessBid.value;
      form["cid"] = businessCid.value;
    }
    const response = await businessUpdateApi(form);
    if (response.code === 200) {
      //   关闭弹窗
      detailsvisible.value = false;
      // console.log(name,'--console.log(name)---')
      //添加成功的提示
      ElMessage.success(response.msg);

      // 更新列表
      await conversion();
      if (useEmpty(form.businessNameses)) {
        businessNameses = "";
      }
      if (useEmpty(form.businessNames)) {
        businessNames = "";
      }
    } else {
      ElMessage.error(response.msg);
    }
  }
};

// 删除
const handelDelete = (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row && row.id) {
        const result = await businessDeleteApi(row.id);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          conversion();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      ElMessage.error(result.msg);
      console.log(err);
    });
};

onMounted(async () => {
  await conversion();
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>
<style>
.el-dialog {
  background-color: #f0f2f5;
}

.el-dialog__footer {
  text-align: center;
}
.converDialog {
  position: absolute;
  left: 15%;
  top: -30px;
}
.el-dialog__header {
  margin-right: 0 !important;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  /* padding-bottom: 15px !important; */
}
</style>

<style scoped lang="scss">
//   .edit-input {
//     padding-right: 100px;
//   }
//   .app-container {
//     flex: 1;
//     display: flex;
//     width: 100%;
//     /* padding: 16px; */
//     box-sizing: border-box;
//   }
//   .cancel-btn {
//     position: absolute;
//     right: 15px;
//     top: 10px;
//   }
</style>
